//
//  LGSEdge.m
//  LogicSim
//
//  Created by Jeremy Pereira on 04/04/2012.
//  Copyright (c) 2012 Jeremy Pereira. All rights reserved.
//

#import "LGSEdge.h"
#import "LGSNode.h"

@interface LGSEdge()

@property (nonatomic, assign) bool value;

@end


@implementation LGSEdge
{
	__weak LGSNode* input;
    __weak LGSNode* output;
    NSString* label;
    bool value;
}

@synthesize input, output, value, label;

-(void) setValue:(bool)newValue affectedNodes: (NSMutableOrderedSet*) affectedNodes
{
    if (newValue != [self value] && affectedNodes != nil && [self output] != nil)
    {
        [affectedNodes addObject: [self output]];
    }
    [self setValue: newValue];
}

-(NSString*) description
{
    return [NSString stringWithFormat: @"%@=>%@", [input label], [output label]];
}

+(void) setArray: (NSArray*) array 
      from32Bits: (uint32_t) bits
   affectedNodes: (NSMutableOrderedSet*) affectedNodes
{
    for (int i = 0 ; i < [array count] && i < 32 ; ++i)
    {
        [[array objectAtIndex: i] setValue: (bits & (1 << i)) != 0
                             affectedNodes: affectedNodes];
    }
}

+(uint32_t) make32BitNumberFromEdgeArray: (NSArray*) bits
{
    uint32_t result = 0;
    for (unsigned int i = 0 ; i < [bits count] && i < 32 ; ++i)
    {
        if ([(LGSEdge*)[bits objectAtIndex: i] value])
        {
            result |= 1 << i;
        }
    }
    return result;
}

+(LGSEdge*) null
{
    static LGSEdge* nullEdge = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        nullEdge = [[LGSEdge alloc] init];
    });
    return nullEdge;
}


@end
